<template>
	<view class="detail">
		<!-- 背景图绑定 -->
		<view class="fixbg" :style="{backgroundImage:'url('+songDetail.al.picUrl+')'}"></view>
		<musichead :title="songDetail.name" :icon="true"></musichead>
		<view class="container" v-show="!isLoading">
			<scroll-view scroll-y="true">
				<!-- 播放页面 -->
				<view class="detail-play" @tap="handleToPlay">
					<!-- 背景图 -->
<!--   图片旋转，在data中定义一个属性去赋予，默认为true；css样式来控制旋转     detail-play-run':isPlayRotate}"     -->
					<image :src="songDetail.al.picUrl" :class="{'detail-play-run':isPlayRotate}"></image>
					<!-- 图中间的按钮 -->
					<text class="iconfont" :class="iconPlay"></text>
					<!-- 圆杆 -->
					<view></view>
				</view>
				
				
				<!-- 歌词列表页面 -->
				<view class="detail-lyric">
					<view class="detail-lyric-wrap" :style="{transform:'translateY('+ -(lyricindex-1)*82 +'rpx)'}">
<!--      :class="{active : lyricindex+1==index}"   设置中间行歌词高亮      -->
						<view class="detail-lyric-wrap-item" v-for="(item,index) in songLyric" :key="index" :class="{active : lyricindex==index}">
              {{item.lyric}}
            </view>

					</view>
				</view>
			</scroll-view>
			
		</view>
	</view>
</template>

<script>
	//引入图标字体
	import '@/common/iconfont.css'
	//引入头部组件
	import musichead from '../../components/music-head/music-head.vue'
	//引入请求
	import {songDetail,songLyric,songUrl} from '../../common/api.js'
	export default {
		data() {
			return {
				//歌曲详情
				songDetail:{
					al:{}
				},
				//歌词
				songLyric:[],
        //播放的容器
        innerAudioContext:{

        },
        //控制首行选中
        lyricindex:0,
        //播放按钮的状态 默认为暂停  单击时候会变成播放
        iconPlay:'icon-zanting',
        //控制是否旋转
        isPlayRotate:true,
        //控制加载
        isLoading:true
			}
		},
		onLoad(options) {
			console.log(options.songId)
			this.getMusic(options.songId)
		},
		components:{
			musichead
		},
    //关闭之后
    onUnload() {
      //清空该对象
      this.innerAudioContext.destroy();
      //清空定时器
      this.cancelLyricIndex();
    },
    //界面隐藏之后
    onHide() {
      //清空该对象
      this.innerAudioContext.destroy();
      //清空定时器
      this.cancelLyricIndex();
    },
		methods: {
			//等这三个请求发送完之后再回调
			getMusic(songId){
        //显示加载中
        uni.showLoading({
          title:'加载中'
        })
				//all方法  可以等所有请求完毕之后再执行
				Promise.all([songDetail(songId),songLyric(songId),songUrl(songId)]).then((res)=>{
					console.log(res)
					//1.获取歌取详情
					//请求成功   
					if(res[0].data.code==200){
						//赋值到本地变量
						this.songDetail=res[0].data.songs[0]
					}

					//2.获取歌词
					//请求成功
					if(res[1].data.code==200){
						//处理歌词
						//使用变量接收原歌词数据
						let lyric=res[1].data.lrc.lyric;
						let result=[];
						//利用正则表达式进行分割
						let re = /\[([^\]]+)\]([^[]+)/g;
						console.log(lyric.match(re))
						//$0该项  $1该项的第一个子项（时间） $2该项的第二个子项（内容） 
						lyric.replace(re,($0,$1,$2)=>{
							//存入数组
							result.push({time:this.formatTimeToSec($1),lyric:$2})
						})
						console.log(result)
						//赋值
						this.songLyric=result
					}
          //3.播放歌曲
          //请求成功
          if(res[2].data.code==200){
            //将播放对象赋值到本地对象
            this.innerAudioContext = uni.createInnerAudioContext();
            //自动播放
            this.innerAudioContext.autoplay = true;
            this.innerAudioContext.src = res[2].data.data[0].url;
            //开始播放之后就监听歌词
            this.listenLyricIndex();

            //播放触发回调
            this.innerAudioContext.onPlay(()=>{
              console.log("开始播放")
              //图标变成暂停  图片开始旋转
              this.iconPlay='icon-zanting';
              this.isPlayRotate=true

            });
            //暂停触发回调
            this.innerAudioContext.onPause(()=>{
              console.log("暂停播放")
              //图标变成播放  图片停止旋转
              this.iconPlay='icon-24gl-playCircle';
              this.isPlayRotate=false;
              //清空定时器
              this.cancelLyricIndex();
            });
          }
          //当歌曲开始播放加载完毕  再关掉提示框
					this.isLoading=false
          uni.hideLoading()
				})
				
			},
      //控制播放还是暂停
      handleToPlay(){
        //如果是暂停状况  点击后就播放
        if (this.innerAudioContext.paused){
          this.innerAudioContext.play();
        }else {
          //如果是播放  点击后就暂停
          this.innerAudioContext.pause();
        }
      },
      //监听歌词的变化
      listenLyricIndex(){
        //先清空定时器
        clearInterval(this.timer);
        this.timer=setInterval(()=>{

          for (let i = 0; i < this.songLyric.length; i++) {
            //如果歌词最后一句的时间比播放器的当前时间小的时候
              if (this.songLyric[this.songLyric.length-1].time < this.innerAudioContext.currentTime){
                    this.lyricindex=this.songLyric.length-1;
                    break;
              }
              //当播放器的时间大于前一个歌词的时间  小于后一个歌词的时间
            //判断歌词在哪个地方
            if (this.songLyric[i].time < this.innerAudioContext.currentTime && this.songLyric[i+1].time>this.innerAudioContext.currentTime){
              //说明歌词匹配
                this.lyricindex=i;
            }

          }
        },500)

      },

    //关闭定时器
      cancelLyricIndex(){
        clearInterval(this.timer)
      },


      //格式化时间方法
      formatTimeToSec(time){
        //以冒号分割
        var arr = time.split(":");
        //console.log(arr)
        //将分钟*60    parseFloat() 将数字转换成一个精确的  toFixed() 保留几位
        return (parseFloat(arr[0]*60)+parseFloat(arr[1])).toFixed(2);
      }



		}
	}
</script>

<style scoped>
.active {
  color: white;
}

/* 播放样式 */
.detail-play {
  width: 580rpx;
  height: 580rpx;
  background: url(~@/static/disc.png);
  background-size: cover;
  margin: 210rpx auto 44rpx auto;
  position: relative;
}

.detail-play image {
  width: 380rpx;
  height: 380rpx;
  border-radius: 50%;
  position: absolute;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  margin: auto;
  animation: 10s linear infinite move;
  animation-play-state: paused;
}

/* 图片旋转 */
.detail-play .detail-play-run {
  animation-play-state: running;
}

@keyframes move {
  from {
    transform: rotate(0deg);
  }

  to {
    transform: rotate(360deg);
  }
}

.detail-play text {
  width: 100rpx;
  height: 100rpx;
  font-size: 100rpx;
  position: absolute;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  margin: auto;
  color: white;
}

.detail-play view {
  position: absolute;
  width: 170rpx;
  height: 266rpx;
  position: absolute;
  left: 60rpx;
  right: 0;
  margin: auto;
  top: -170rpx;
  background: url(~@/static/needle.png);
  background-size: cover;
}

/* 歌词样式 */
.detail-lyric {
  font-size: 32rpx;
  line-height: 82rpx;
  height: 246rpx;
  text-align: center;
  overflow: hidden;
  color: #6f6e73;
}
/*
歌词每0.5s滚动一次*/
.detail-lyric-wrap {
  transition: 0.5s;
}

.detail-lyric-wrap-item {
  height: 82rpx;
}

.detail-lyric-wrap-item-art {
  color: white;
}
</style>
